<?php



function authCAS($config) {

    
	require_once(dirname(__FILE__).'/CAS/CAS.php');

	// get module configuration

    $cas_validate=true;
    $cas_version=CAS_VERSION_2_0;
    $cas_language='english';



//    phpCAS::setDebug();

    
    phpCAS::client($cas_version,$config->cashostname,(int)$config->casport,$config->casbaseuri,false);
    phpCAS::setLang($cas_language);
    
    error_log("CAS: Entering");
    $check = phpCAS::isSessionAuthenticated();
    phpCAS::forceAuthentication();
    $NetUsername = phpCAS::getUser();  //this stores their network user id    
    error_log("CAS: Exiting $NetUsername");
    return $NetUsername;

}

function logoutCAS($config,$wwwroot) {


	require_once(dirname(__FILE__).'/CAS/CAS.php');

	// get module configuration

	$cas_validate=true;
	$cas_version=CAS_VERSION_2_0;
	$cas_language='english';


	phpCAS::client($cas_version,$config->cashostname,(int)$config->casport,$config->casbaseuri,false);

	error_log("CAS: Logout");
	phpCAS::logout($wwwroot);
	error_log("CAS: Logout Exit");
	return true;
}



/**
 * Take a user name
 *
 * @return user object from the user table if one exist
 */
function cas_getUserId( $username, $attr) {


    $uid = isset($attr['textUid']) ? $attr['textUid'] : str_replace(".", "",$username);  

    $result = get_record_select('users',
				"username = ? AND active = ? AND user_type = ? ",
				array($uid,'yes','person')
	);

    return $result;
}

/**
 * insert user into elgg user table
 *
 * Get user info from db
 * Tries to insert, otherwise return error
 *
 * @return user
 */

function cas_insertUser($username, $casUser, $config) {
	
	   
//     $name = $attr['cn'];
//     $uname = !empty($attr['textuid']) ? $attr['textuid'] : str_replace(".", "",$username);
//     $email = $attr['mail'];

	$name = $casUser->name;
	$uname = !empty($casUser->username) ? $casUser->username : $username;
	$email = $casUser->email;
    
    $password = md5($uname . $email);
    
    
	$user = new ElggUser();
	$user->username = $uname;
	$user->email = $email;
	$user->name = $name;
	$user->access_id = 2;
	$user->salt = generate_random_cleartext_password(); // Note salt generated before password!
	$user->password = generate_user_password($user, $password); 
	
	$user->save();

	$guid = $user->guid;
	$obj = get_entity($guid);
	
    if (isset($config->casadminuser) && ($config->casadminuser == $username)) {
	
    	if ( ($obj instanceof ElggUser) && ($obj->canEdit()))
    	{
    		$obj->admin = 'yes';
    		if ($obj->admin)
    			system_message(elgg_echo('admin:user:makeadmin:yes'));
    		else
    			register_error(elgg_echo('admin:user:makeadmin:no'));
    	}
    	else
    		register_error(elgg_echo('admin:user:makeadmin:no'));

    }

	return $user;
}

/**
* Log in
*
* @param user entity $user
* @param true|false $persistent
* @return true|false
*/
function cas_do_login($user, $persistent = false) {
             
    $_SESSION['user'] = $user;
    $_SESSION['guid'] = $user->getGUID();
    $_SESSION['id'] = $_SESSION['guid'];
    $_SESSION['username'] = $user->username;
    $_SESSION['name'] = $user->name;
    
    $code = (md5($user->name . $user->username . time() . rand()));
    $user->code = md5($code);
    $user->save();
    
    $_SESSION['code'] = $code;
    //if (!empty($persistent)) {
    
    setcookie("elggperm", $code, (time()+(86400 * 30)),"/");
    
    //}
    // set_login_fields($user->id);

    return true; 
   
}



/**
 * search ldap server
 *
 * Tries connect to specified ldap server.
 * Returns connection result or error.
 *
 * @return search result
 */
function cas_ldapSearch( $uid ) {
   global $CONFIG, $messages;
   	$config = elgg_get_plugin_from_id('cas_auth');


    // Connect to the ldap server now
    $ldap_connection = cas_ldapConnect();

    if ( !$ldap_connection ) {
	$messages[] = __gettext("Unable to connect to LDAP server");

	return null;
    }


    $ldap_context = $config->ldap_context;
    $ldap_search_pattern = "(uid=$uid)";
    $ldap_fields_wanted = array('uid', 'cn', 'mail', 'textuid');
    
    $ldap_context = 'ou=People,dc=athabascau,dc=ca';

    $ldap_result = @ldap_search($ldap_connection, 
				$ldap_context, 
				$ldap_search_pattern,
				$ldap_fields_wanted);

    /* check and push results */
    $records = ldap_get_entries($ldap_connection, $ldap_result);
    // NOTE: ldap_get_entries returns array indices in lowercase.

    if ( !$records ) {
	$messages[] = 'No records found.';
	return null;
    }

    $record["dn"] = $records[0]["dn"];
    $record["cn"] = $records[0]["cn"][0];
    $record["uid"] = $records[0]["uid"][0];
    $record["mail"] = $records[0]["mail"][0];
    if ( isset($records[0]["textuid"][0])) {
			 $record["textUid"] = $records[0]["textuid"][0];
    }

    ldap_close($ldap_connection);
   
    return $record;
}

/**
 * connects to ldap server
 *
 * Tries connect to specified ldap server.
 * Returns connection result or error.
 *
 * @return connection result
 */

function cas_ldapConnect($binddn='',$bindpwd=''){

    global $CONFIG, $messages;

	$config = find_plugin_settings('cas_auth');


    //Select bind password, With empty values use
    //ldap_bind_* variables or anonymous bind if ldap_bind_* are empty
    if ($binddn == '' AND $bindpwd == '') {
        if (!empty($config->ldap_bind_dn)){
	    $binddn = $config->ldap_bind_dn;
        }
        if (!empty($config->ldap_bind_pwd)){
	    $bindpwd = $config->ldap_bind_pwd;
        }
    }



    if (!isset($config->ldaphostname)) {
	$messages[] = __gettext("\LDAP server information has not been provided. Aborting now!");
	return false;
    }
    
    $server = trim($config->ldaphostname);

    if (!$server){
	$messages[] = __gettext("\LDAP server information has not been  provided. Aborting now!");
	return false;
    }

    $ldapport = 389;
    if(!empty($config->ldapport)){
    	$ldapport = $config->ldapport;
    }
    
    $connresult = ldap_connect($server,$ldapport);
    //ldap_connect returns ALWAYS true
 
    if (!empty($config->ldapversion)) {
	ldap_set_option($connresult, LDAP_OPT_PROTOCOL_VERSION, $config->ldapversion);
    }

    if (!empty($binddn)){
	//bind with search-user
	//$debuginfo .= 'Using bind user'.$binddn.'and password:'.$bindpwd; 
	$bindresult=ldap_bind($connresult, $binddn,$bindpwd);
    } else {
	//bind anonymously 
	$bindresult=@ldap_bind($connresult);
    }
       
    if (!empty($config->ldap_opt_deref)) {
	ldap_set_option($connresult, LDAP_OPT_DEREF, $config->ldap_opt_deref);
    }

    if ($bindresult) {
	return $connresult;
    }

    // At this point, could not connect to ldap. Hence lets get some
    // debug information.   
    $debuginfo .= "<br/>Server: '$server'<br /> Bind result: '" . ldap_error($connresult) . "' <br />";  
    //If any of servers are alive we have already returned connection
    $messages[] = "LDAP-module cannot connect to LDAP server : $debuginfo";
    
    return false;
}


/**
 * Looking for user
 * @param unknown $uid
 */
function cas_mysqlSearch($uid) {
	global $CONFIG, $messages;
	$config = elgg_get_plugin_from_id('cas_auth');
	
	$con = mysqli_connect($config->mysqlhostname, $config->mysqluser, $config->mysqlpass, $config->mysqldbname, $config->mysqlport);
	
	// Check connection
	if (mysqli_connect_errno())
	{
		$messages[] = __gettext("Unable to connect to DB server");
		return null;
	}
	
	// Select User
	$sql="SELECT * from ".$config->mysqltbname." where ".$config->mysqlfield."='".$uid."'";
	$records = mysqli_query($con,$sql);
	
	if ( !$records ) {
		$messages[] = 'No records found.';
		return null;
	}
	
	$user = new ElggUser();
	
	while($row = mysqli_fetch_array($records))
	{
		$user->name =  $row['firstname'].' '.$row['lastname'];
		$user->username = $row[$config->mysqlfield];
// 		$pos = strpos($user->username, '@');
// 		if($pos) {
// 			$user->username = substr($user->username, 0, $pos);			
// 		}
		
		$user->email =  $row['email'];
		$user->language =  $row['language'];
		break;
	}
	
	mysqli_close($con);
	return $user;
}

?>